use std::{env, io};
use std::sync::Mutex;
use actix_web::web;
use chrono::NaiveDateTime;
// use dotenv::dotenv;
// use crate::models::

// use chrono::

use sqlx::PgPool;
use sqlx::postgres::PgPoolOptions;
use crate::error::MyError;
use crate::models::course::Course;
use crate::states::AppState;

//
pub async fn get_course_by_teacher_id_db(pool: &PgPool, teacher_id: i32) -> Result<Vec<Course>, MyError> {
    let rows = sqlx::query_as!(Course , r#"
    select id , teacher_id ,name , time from course where teacher_id =$1
    "#, teacher_id)
        .fetch_all(pool)
        .await?;  // ? 表示错误传播到上级


    let res:Vec<_> = rows.iter().map(|r| Course {
        id: r.id,
        teacher_id: r.teacher_id,
        name: r.name.clone(),
        time: r.time,
    }).collect();


    if res.len() == 0 {
        Err(MyError::NotFound("记录不存在".to_string()))
    } else {
        Ok(res)
    }
}


pub async fn get_course_detail_db(pool: &PgPool, course_id: i32) -> Result<Course, MyError> {
    let detail = sqlx::query!( r#"
    select id , teacher_id ,name , time from course where id =$1
    "#, course_id)
        .fetch_one(pool)
        .await?;


    let c = Course {
        id: detail.id,
        name: detail.name.to_string(),
        teacher_id: detail.teacher_id,
        time: detail.time,
    };

    Ok(c)
}


pub async fn add_course_db(pool: &PgPool, new_course: Course) -> Result<(), MyError> {
    let rows = sqlx::query!(r#"
    insert into   course (id , teacher_id , name )  values ( $1,$2,$3)
    "#, new_course.id , new_course.teacher_id , new_course.name )
        .fetch_one(pool)
        .await?;

    Ok(())
}